package org.snake.exam.eg.clh;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.locks.Lock;

public class ClhSpinLockTest {

    private static int count = 0;

    private static void testLock(Lock lock) {
        try {
            lock.lock();

            System.out.println("任务启动线程名称:" + Thread.currentThread().getName() + " 任务开始时统计数:" + count + " 任务执行时间:" + System.currentTimeMillis());

            for (int i = 0; i < 100; i++) {
                count++;
            }

            System.out.println("任务启动线程名称:" + Thread.currentThread().getName() + " 任务结束时统计数:" + count);
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        int workerThreadNums = 5;

        // 这个锁是需要每个相关线程都需要持有的
        final ClhSpinLock clhSpinLock = new ClhSpinLock();
        // 这个是一个栅栏 目的是等到所有线程都执行完 看结果
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(workerThreadNums, () -> System.out.println("最终结果:" + count));

        for (int i = 0; i < workerThreadNums; i++) {
            new Thread(() -> {
                testLock(clhSpinLock);

                try {
                    cyclicBarrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }).start();
        }
    }
}
